﻿// Copyright (c) 2009 Kjetil Eraker Samuelsen
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.

using System;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

namespace Ksamuelsen.Office.Outlook.Addin.VDialer.Interop {
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    internal struct CREDENTIAL {
        public UInt32 Flags;
        public CRED_TYPE Type;
        public IntPtr TargetName;
        public IntPtr Comment;
        public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
        public UInt32 CredentialBlobSize;
        public IntPtr CredentialBlob;
        public UInt32 Persist;
        public UInt32 AttributeCount;
        public IntPtr Attributes;
        public IntPtr TargetAlias;
        public IntPtr UserName;

        internal static CREDENTIAL CreateCredential(string key, string username, string password, CRED_TYPE type, CRED_PERSIST persist) {
            CREDENTIAL cred   = new CREDENTIAL();
            byte[]     bPassw = Encoding.Unicode.GetBytes(password);

            cred.AttributeCount     = 0;
            cred.Attributes         = IntPtr.Zero;
            cred.Comment            = IntPtr.Zero;
            cred.TargetAlias        = IntPtr.Zero;
            cred.Type               = type;
            cred.Persist            = (UInt32)persist;
            cred.CredentialBlobSize = (UInt32)bPassw.Length;
            cred.TargetName         = Marshal.StringToCoTaskMemUni(key);
            cred.CredentialBlob     = Marshal.StringToCoTaskMemUni(password);
            cred.UserName           = Marshal.StringToCoTaskMemUni(username);
            return cred;
        }
    }

}
